package com.timothy.service;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;

import com.timothy.answer.BaseAnswer;
import com.timothy.answer.BaseStationSelection;

public class MessageSender {
	public static String PC_IP;
	public static int PC_PORT = 9999;
	
	public static final String Get_Base_Stations = "<Message Type=\"GetBaseStations\">" +
													  "<Content></Content>" +
												   "</Message>";
	
	public static final String ST_Two_Button_Alpha_Question_Result = "<Message Type=\"QuestionResult\">" +
													"<Content>" + 
    													"<SlideIndex>%d</SlideIndex>" +
    													"<Value>%s</Value>" + 
													"</Content>" + 
												  "</Message>";
    
	public static final String Base_Station_Selection = "<Message Type=\"Authorize\">" +
        													"<Content>" + 
        														"<BaseStation>%s</BaseStation>"+
        														"<Password>%s</Password>"+
        													"</Content>" +
        												"</Message>";
	
	private static String HEADER = "<Header>" +
	  									"<Phone IPAddress=\""+getIp()+"\" Name=\"\" Port=\""+PC_PORT+"\"></Phone>" +
	  								"</Header>";
	public static boolean sendMessage(String command){
		command = addHeader( command );
		try {
			Socket socket = new Socket(PC_IP, Integer.valueOf(PC_PORT));
			if(!socket.isConnected()){
				return false;
			}
			PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
			out.print(command);
			out.close();
			socket.close();
			return true;
		} catch (Exception ex) {
			ex.printStackTrace();
			return false;
		}
	
	}
	
	public static boolean sendAnswer( BaseAnswer answer ) {
		String message = answer.toMessage();
		return sendMessage( message ); 
	}
	
	public static boolean sendBaseStationSelection(BaseStationSelection bss) {
		HEADER = HEADER.replaceAll("Name=\"[^\"]*\"", "Name=\""+bss.getUserName()+"\"");
		return sendMessage( bss.toMessage() );
	}
	
	private static String getIp(){
        String localip=null;//本地IP，如果没有配置外网IP则返回它
        String netip=null;  //外网IP
        try {
            Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
            while( netInterfaces.hasMoreElements() ) {
                NetworkInterface ni = netInterfaces.nextElement();
                Enumeration<InetAddress> address = ni.getInetAddresses();
                while( address.hasMoreElements() ) {
                    InetAddress ip=address.nextElement();
                    if( ip.isLoopbackAddress() || ip.getHostAddress().indexOf(":")!=-1 )
                        continue;
                    
                    if( ip.isSiteLocalAddress() ){ //内网IP
                        localip=ip.getHostAddress();
                    } else { //外网IP     
                        netip = ip.getHostAddress();
                        break;
                    }
                }
                
                if( netip!=null )
                    break;
            }
        } catch (SocketException e) {
        }
        
        if(  netip!=null  )
            return netip;
        else if ( localip!=null )
            return localip;
        else
            return "127.0.0.1";
    } 
	
	private static String addHeader( String message ) {
		int index = message.indexOf('>')+1;
		return message.substring(0, index) + HEADER + message.substring(index) ;
	}
}
